package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import javafx.beans.property.ReadOnlyBooleanWrapper;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService  workspaceService;

    @Autowired
    private BusinessDataVO businessDataVO;

    @Override
    public TurnoverReportVO getTurnoverStatics(LocalDate begin, LocalDate end) throws Exception {
        //存放日期
        List<LocalDate> dateList =new ArrayList<>();
        dateList.add(begin);

        if (begin.isAfter(end)){
            throw new Exception("开始时间大于结束时间");
        }

        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }

        List<Double> turnoverList=new ArrayList<>();
        for(LocalDate date: dateList){
            LocalDateTime beginTime=LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            HashMap map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);

            Double turnover = orderMapper.sumByMap(map);

            turnover=turnover==null?0.0:turnover;

            turnoverList.add(turnover);

        }


        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();

    }


    @Override
    public UserReportVO getUserStatics(LocalDate begin, LocalDate end) throws Exception {
        //存放日期
        List<LocalDate> dateList =new ArrayList<>();
        dateList.add(begin);

        if (begin.isAfter(end)){
            throw new Exception("开始时间大于结束时间");
        }

        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }


        ArrayList<Integer> newUserList = new ArrayList<>();

        ArrayList<Integer> totalUserList = new ArrayList<>();

        for(LocalDate date : dateList){
            LocalDateTime beginTime = LocalDateTime.of(date,LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date,LocalTime.MAX);

            Map map = new HashMap<>();
            map.put("end",endTime);

            //总
            Integer totalUser = userMapper.countByMap(map);

            map.put("begin",beginTime);

            Integer newUser = userMapper.countByMap(map);

            newUserList.add(newUser);
            totalUserList.add(totalUser);
        }

        return UserReportVO.builder().dateList(StringUtils.join(dateList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .build();
    }

    @Override
    public OrderReportVO getOrderStatics(LocalDate begin, LocalDate end) throws Exception {
        //存放日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        if (begin.isAfter(end)) {
            throw new Exception("开始时间大于结束时间");
        }

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Integer> orderCountList = new ArrayList();
        List<Integer> validCountList = new ArrayList();
        for(LocalDate date : dateList){
            LocalDateTime startTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Integer allCount = getOrderCount(startTime, endTime, null);
            Integer validCount = getOrderCount(startTime, endTime, Orders.COMPLETED);


            orderCountList.add(allCount);
            validCountList.add(validCount);
        }

        //求和
        Integer orderAllCount = orderCountList.stream().reduce(Integer::sum).get();
        Integer validOrderAllCount = validCountList.stream().reduce(Integer::sum).get();

        //完成率计算
        Double validRate=0.0;
        if(orderAllCount!=0){
            validRate = validOrderAllCount.doubleValue()/orderAllCount;
        }

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validCountList,","))
                .totalOrderCount(orderAllCount)
                .validOrderCount(validOrderAllCount)
                .orderCompletionRate(validRate)
                .build();

    }

    private Integer getOrderCount(LocalDateTime begin,LocalDateTime end,Integer status){
        Map map = new HashMap();
        map.put("begin",begin);
        map.put("end",end);
        map.put("status",status);

        return orderMapper.countByMap(map);
    }

    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> salesTopList = orderMapper.getSalesTop(beginTime, endTime);

        List<String> nameList = new ArrayList();
        List<Integer> numberList = new ArrayList();

        for(GoodsSalesDTO goodsSalesDTO : salesTopList){
            nameList.add(goodsSalesDTO.getName());
            numberList.add(goodsSalesDTO.getNumber());
        }

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) {

        LocalDate beginDate = LocalDate.now().minusDays(30);
        LocalDate endDate = LocalDate.now().minusDays(1);

        LocalDateTime begin = LocalDateTime.of(beginDate, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(endDate, LocalTime.MAX);

        workspaceService.getBusinessData(begin,end);

        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);

            XSSFSheet sheet1 = excel.getSheet("sheet1");

            //表头数据
            sheet1.getRow(1).getCell(1).setCellValue(beginDate+"至"+endDate);

            XSSFRow row = sheet1.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            XSSFRow row1 = sheet1.getRow(4);
            row1.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row1.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = beginDate.plusDays(i);
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                XSSFRow row2 = sheet1.getRow(7 + i);
                row2.getCell(1).setCellValue(date.toString());
                row2.getCell(2).setCellValue(businessData.getTurnover());
                row2.getCell(3).setCellValue(businessData.getValidOrderCount());
                row2.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row2.getCell(5).setCellValue(businessData.getUnitPrice());
                row2.getCell(6).setCellValue(businessData.getNewUsers());
            }

            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);

            excel.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }




    }
}
